import publicComponent from "@/basa/components/public";
import { cloneDeep } from "lodash";
import { mapGetters, mapActions, mapState } from "vuex";
import { postGetEnum, checkConcBillReference } from "@/basa/api";
import { generateUUID, proxyDateFormat } from "@/basa/utils";
import { showLoading } from "@/basa/utils/public";
export default contractType => ({
  props: {
    detail: {
      type: Object,
      default: () => { }
    },
    isShow: {
      type: Boolean
    }
  },
  components: {
    dialogMultiSelectTable: publicComponent.dialogMultiSelectTable,
    listSettingsBtn: publicComponent.listSettingsBtn,
    listSettings: publicComponent.listSettings,
    chooseMaterials: publicComponent.chooseMaterialsCatalogue
  },
  data() {
    return {
      Enum: {
        taxRatePercentList: [],
        currentMeasuringUnitList: []
      },
      purchaseList: [],
      listTableData: [],
      materialVisible: false,
      dialogVisible: false,
      form: {
        a: "",
        b: "",
        c: "",
        d: ""
      },
      programmeOptionalParams: {},
      planOptionalParams: {},
      rowParams: {},
      taxRateParams: null,
      agreementSelectTableList: [], // 回显框架弹窗中已选择的数据
      planSelectTableList: [], // 回显采购计划弹窗中已选择的数据
      programmeSelectTableList: [], // 回显采购方案弹窗中已选择的数据
      isMultiRate: true, // 是否多税率 是(false)  否(true)
      multiRateStatus: false,
      isMultiShow: false,
      listSettingsDialogTitle: "批量设置",
      listSettingsStatus: "",
      listSettingsDetail: {},
      listSettingsMap: {
        taxRate: "税率",
        address: "交货地点",
        deliveryTime: "交货时间",
        manufacturer: "生产厂家/品牌"
      },
      tableLoading: null,
      showListNum: 0,
      timer: null,
    };
  },
  created() {
    this.init();

    this.$once("hook:beforeDestroy", () => {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    });
  },
  methods: {
    init() {
      this.postGetEnum();
      this.setShowDoubleTable(false);
      if (!(contractType === 'draft' && this.detail.state === "create")) this.editInit();
    },

    editInit() {
      this.purchaseList = this.detail.smpConcMatLessList.map(n => ({
        ...n,
        deliveryTime: n.deliveryTime ? proxyDateFormat(n.deliveryTime) : "",
        currentUnitPriceIncludeTax:
          n.currentUnitPriceIncludeTax !== null
            ? Number(n.currentUnitPriceIncludeTax).toFixed(2)
            : "", // 含税单价
        currentUnitPriceIncludeTaxStr: n.currentUnitPriceIncludeTax, // 含税单价
        currentNum:
          n.currentNum !== null ? Number(n.currentNum).toFixed(3) : "",
        currentUnitPriceExcludeTax:
          n.currentUnitPriceExcludeTax !== null
            ? Number(n.currentUnitPriceExcludeTax).toFixed(2)
            : "",
        currentChangeAmtExcludeTax:
          n.currentChangeAmtExcludeTax !== null
            ? Number(n.currentChangeAmtExcludeTax).toFixed(2)
            : "",
        currentChangeAmtIncludeTax:
          n.currentChangeAmtIncludeTax !== null
            ? Number(n.currentChangeAmtIncludeTax).toFixed(2)
            : "",
        rate: n.rate !== null ? Number(n.rate).toFixed(2) : "",
        manufacturerDisabled: true, // 生产厂家禁用
        onlyId: generateUUID(),
        priceType: n.priceType ? Number(n.priceType) : n.priceType,
        address:
          (n.deliveryAreaName || "") +
          (n.provinceName || "") +
          (n.cityName || "") +
          (n.countyName || "") +
          (n.deliveryPoints || "") // 交货地点
      }));

      // this.setEchoProtocalData(data.smpConcMatLessList);
      this.setDetailedTableList();
    },

    // 普通计算清空
    clearOrdinaryCompute(row) {
      if (!this.getInputRule(row.currentNum)) {
        row.currentNum = "";
      }
      if (!this.getInputRule(row.currentUnitPriceIncludeTax)) {
        row.currentUnitPriceIncludeTax = "";
      }
      row.currentChangeAmtIncludeTax = "";
      row.currentChangeAmtExcludeTax = "";
      row.currentUnitPriceExcludeTax = "";
      row.rate = "";
      this.$bus.$emit("setPriceSum", {
        setContractPriceIncludeTax: "",
        setContractPriceExcludeTax: ""
      });
    },

    // 给表头加必选标识
    must({ $rowIndex, column }) {
      if (this.getTableHeadRuleNode.includes(column.title)) {
        return "must";
      }
    },

    // 获取枚举
    postGetEnum() {
      const arr = [
        "getTaxRateDict", // 查询税率字典数据
        "qryBasuomOtherDict" // 查询计量单位字典数据
      ];
      for (let i = 0; i < arr.length; i++) {
        const element = arr[i];
        postGetEnum(element).then(res => {
          this.Enum[Object.keys(this.Enum)[i]] = res.data.data;
        });
      }
    },

    handleChange(index, type, row) {
      const temp = this.purchaseList[index];
      if (type === "taxRatePercent") {
        const obj = this.Enum.taxRatePercentList.find(
          _ => _.dicValue === temp[type]
        );
        temp.taxRateCode = obj.dicKey;
        if (temp[type] !== "免税") {
          const newVal = temp[type].match(/\d+(.\d+)?/g)[0];
          temp.taxRate = Number(newVal) / 100;
        } else {
          temp.taxRate = Number(obj.dicKey);
        }
      } else {
        temp[`${type}Code`] = this.Enum[`${type}List`].find(
          _ => _.dicValue === temp[type]
        ).dicKey;
      }
      this.testColumn(null, row, "blur", "currentUnitPriceIncludeTax");
    },

    // 设置框架协议到清单
    getAgreementDataToPurchaseList(arr, status) {
      this.agreementSelectTableList = arr;
      const pushData = arr.map((n, i) => ({
        ...n,
        isConversion: 0, // 是否转换过单位 => 0 未转换 1 转换
        onlyId: generateUUID(),
        matResource: "0", // 0-框架协议，1=寻源结果，2=采购计划 3,=其他
        taxRate: 0, // 重置税率
        baseProportion: 1,
        baseNum: 1,
        priceType: n.pricetype,
        currentChangeAmtExcludeTax: "", // 重置不含税金额
        currentChangeAmtIncludeTax: "", // 重置含税金额
        currentUnitPriceIncludeTax:
          n.pricetype === 0 ? n.currentUnitPriceIncludeTax : "", // 重置含税单价
        currentUnitPriceIncludeTaxStr: n.currentUnitPriceIncludeTax, // 含税单价
        currentUnitPriceExcludeTax: "", // 不含税单价
        rate: 0, // 税额
        address:
          (n.deliveryAreaName || "") +
          (n.provinceName || "") +
          (n.cityName || "") +
          (n.countyName || "") +
          (n.deliveryPoints || ""), // 交货地点
        manufacturer: "",
        currentNum: n.currentNum ? Number(n.currentNum).toFixed(3) : "", // 采购数量
        matDescribe: n.matDescribe ?? "", // 说明
        deliveryTime: n.deliveryTime ?? "", // 交货时间
        manufacturerDisabled: true, // 禁用生产厂家输入框
        smpBrandRelationReqBOS: []
      }));

      if (status === "cover") {
        // 过滤出物资的清单
        const notPkPurmatdetlList = this.purchaseList.filter(
          _ => !_.pkPurmatdetl
        );

        this.purchaseList = [...notPkPurmatdetlList, ...pushData];
      } else {
        this.purchaseList.push(...pushData);
      }

      this.purchaseList.map(item => {
        if (item.matResource === "0") {
          this.testColumn(null, item, "blur", "currentUnitPriceIncludeTax");
        }
      });

      this.setProtocalCode(arr[0]);
      this.setDetailedTableList();
    },

    // 设置特殊协议
    setSpecialProtocal(temp) {
      // 取清单中协议的第一条
      const firstAgreement = this.purchaseList.find(_ => _.matResource === "0");
      if (!firstAgreement) {
        return this.getAgreementDataToPurchaseList(temp);
      }
      // 判断新选择的协议和清单中已选择的协议的第一条 code 是否相同
      const tempState = temp.every(
        _ => _.protocalCode === firstAgreement.protocalCode
      );
      if (tempState) return this.getAgreementDataToPurchaseList(temp);
      // 不满足
      this.$confirm("此操作将清空采购清单中已引用的数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 最后进行赋值
          this.getAgreementDataToPurchaseList(temp, "cover");
        })
        .catch(() => {
          this.setProtocalCode(this.getProtocalObj);
        });
    },

    // 采购计划选择确认
    planConfirm(data) {
      // this.planSelectTableList = data;
      // const filterPlan = new Set(this.purchaseList.map(_ => _.pkPurmatdetl));

      // if (!data.length) {
      //   this.purchaseList.map((n, i) => {
      //     if (filterPlan.has(n.pkPurmatdetl)) {
      //       this.purchaseList.splice(i, 1);
      //     }
      //   });
      // } else {
      // if (this.purchaseList.length) {
      // const isHomology = this.purchaseList.every(
      //   n => n.matResource === '2'
      // );
      // if (!isHomology) {
      //   return this.$showErrorMessage(
      //     "已选择框架协议或者采购方案，添加清单失败"
      //   );
      // }
      // }

      if (data.length) {
        this.purchaseList.push(
          ...data.map((n, i) => ({
            ...n,
            isConversion: 0, // 是否转换过单位 => 0 未转换 1 转换
            onlyId: generateUUID(),
            matResource: "2", // 0-框架协议，1=寻源结果，2=采购计划 3,=其他
            taxRate: 0, // 重置税率
            baseProportion: 1,
            baseNum: 1,
            currentNum: n.currentNum ? Number(n.currentNum).toFixed(3) : "",
            matDescribe: n.matDescribe ?? "", // 说明
            deliveryTime: n.deliveryTime ?? "", // 交货时间
            currentChangeAmtExcludeTax: "", // 重置不含税金额
            currentChangeAmtIncludeTax: "", // 重置含税金额
            currentUnitPriceIncludeTax: this.isCurrentNumShow(n)
              ? n.currentUnitPriceIncludeTax
              : "", // 重置含税单价
            materialsName: n.matname, // 物装编码
            materialsCode: n.matcode,
            baseMeasuringUnitCode: n.uom,
            purchasePlanCode: n.pcode, // 采购计划
            purchasePlanName: n.pname,
            purchasePlanId: n.pkPurplan, // 采购计划id
            address:
              (n.deliveryAreaName || "") +
              (n.provinceName || "") +
              (n.cityName || "") +
              (n.countyName || "") +
              (n.deliveryPoints || ""), // 交货地点
            deliveryPoints: n.deliveryPoints ?? "",
            manufacturer: "",
            manufacturerDisabled: true, // 禁用生产厂家输入框
            smpBrandRelationReqBOS: []
          }))
        );

        this.setDetailedTableList();
      }
      // }
    },

    // 采购方案选择确认
    programmeConfirm(data) {
      // this.programmeSelectTableList = data;
      // const filterProgramme = new Set(
      //   this.purchaseList.map(_ => _.pkPurmatdetl)
      // );

      // if (!data.length) {
      //   this.purchaseList.map((n, i) => {
      //     if (filterProgramme.has(n.pkPurmatdetl)) {
      //       this.purchaseList.splice(i, 1);
      //     }
      //   });
      // } else {
      // if (this.purchaseList.length) {
      // const isHomology = this.purchaseList.every(
      //   n => n.matResource === '1'
      // );
      // if (!isHomology) {
      //   return this.$showErrorMessage(
      //     "已选择框架协议或者采购计划，添加清单失败"
      //   );
      // }
      // }
      if (data.length) {
        this.purchaseList.push(
          ...data.map((n, i) => ({
            ...n,
            isConversion: 0, // 是否转换过单位 => 0 未转换 1 转换
            onlyId: generateUUID(),
            matResource: "1", // 0-框架协议，1=寻源结果，2=采购计划 3,=其他
            taxRate: 0, // 重置税率
            baseProportion: 1,
            baseNum: 1,
            currentNum: n.currentNum ? Number(n.currentNum).toFixed(3) : "",
            currentChangeAmtExcludeTax: "", // 重置不含税金额
            currentChangeAmtIncludeTax: "", // 重置含税金额
            deliveryTime: n.deliveryTime ? proxyDateFormat(n.deliveryTime) : "", // 交货时间
            address:
              (n.deliveryAreaName || "") +
              (n.provinceName || "") +
              (n.cityName || "") +
              (n.countyName || "") +
              (n.deliveryPoints || ""), // 交货地点
            deliveryPoints: n.deliveryPoints ?? "", // 详细地址
            manufacturer: "",
            matDescribe: n.matDescribe ?? "", // 说明
            manufacturerDisabled: true, // 禁用生产厂家输入框
            smpBrandRelationReqBOS: []
          }))
        );

        this.purchaseList.map(item => {
          if (item.matResource === "1") {
            this.testColumn(null, item, "blur", "currentUnitPriceIncludeTax");
          }
        });

        this.setDetailedTableList();
      }

      // }
    },
    // 选择材料
    handleChooseMaterials() {
      // 打开新增物资清单页面
      this.$refs.materialsFormVisible.dialogFormVisible = true;
    },
    // 物资清单选择确认
    handleSelect(arr) {
      if (arr.length) {
        this.purchaseList.push(
          ...arr.map((n, i) => ({
            ...n,
            isConversion: 0, // 是否转换过单位 => 0 未转换 1 转换
            onlyId: generateUUID(),
            baseProportion: 1,
            currentProportion: "",
            matResource: "3", // 0-框架协议，1=寻源结果，2=采购计划 3,=其他
            taxRate: 0,
            baseNum: 1,
            matDescribe: "", // 说明
            currentNum: "", // 数量
            deliveryTime: "", // 交货时间
            currentChangeAmtIncludeTax: "", // 含税金额
            currentChangeAmtExcludeTax: "", // 不含税金额
            currentUnitPriceExcludeTax: "", // 不含税单价
            currentUnitPriceIncludeTax: "", // 含税单价
            rate: 0, // 税额
            materialsName: n.matName, // 物装编码
            materialsCode: n.matNum,
            thirdCategoriesOfName:
              n.parentCategoriesName || n.thirdCategoriesOfName, // 三级
            thirdCategoriesOfCode:
              n.parentCategoriesCode || n.thirdCategoriesOfCode,
            firstCategoriesOfName:
              n.majorCategoriesName || n.firstCategoriesOfName, // 大类
            firstCategoriesOfCode:
              n.majorCategoriesCode || n.firstCategoriesOfCode,
            specifications: n.categoryName, // 规格型号
            specificationsCode: n.categoryCode,
            baseMeasuringUnit: n.unitStr, // 基础计量单位
            baseMeasuringUnitCode: n.unit,
            currentMeasuringUnit: n.unitStr, // 计量单位
            currentMeasuringUnitCode: n.unit,
            manufacturer: "",
            manufacturerDisabled: true, // 禁用生产厂家输入框
            smpBrandRelationReqBOS: [],
            deliveryPoints: ""
          }))
        );

        this.setDetailedTableList();
      }
    },
    // 采购清单选中数据
    listSelectTable(val) {
      this.listTableData = val;
      this.listSettingsDialogTitle = "批量设置";
    },

    // 复制
    handleCopy() {
      if (!this.listTableData.length) {
        this.$showErrorMessage("未选中复选框");
      } else {
        this.purchaseList.push(
          ...this.listTableData.map((n, i) => ({
            materialsCode: n.materialsCode, // 物资编码
            materialsName: n.materialsName, // 物资名称
            matDescribe: n.matDescribe, // 物资说明
            thirdCategoriesOfName: n.thirdCategoriesOfName, // 三级
            thirdCategoriesOfCode: n.thirdCategoriesOfCode,
            firstCategoriesOfName: n.firstCategoriesOfName, // 大类
            firstCategoriesOfCode: n.firstCategoriesOfCode,
            baseMeasuringUnit: n.baseMeasuringUnit, // 基础计量单位
            baseMeasuringUnitCode: n.baseMeasuringUnitCode, // 基础计量单位
            currentMeasuringUnit: n.baseMeasuringUnit, // 当前计量单位
            currentMeasuringUnitCode: n.baseMeasuringUnitCode, // 当前计量单位
            specificationsCode: n.specificationsCode ?? "",
            currentChangeAmtIncludeTax: "", // 含税金额
            currentChangeAmtExcludeTax: "", // 不含税金额
            currentUnitPriceExcludeTax: "", // 不含税单价
            currentUnitPriceIncludeTax: "", // 含税单价
            currentNum: "", // 数量
            manufacturerDisabled: true,
            matResource: n.matResource,
            priceType: 4,
            rate: 0, // 税额
            id: null,
            isConversion: 0, // 是否转换过单位 => 0 未转换 1 转换
            onlyId: generateUUID()
          }))
        );

        this.setDetailedTableList();
        // 重置复选框选中的数据
        this.listTableData = [];
      }
    },

    // 删除
    handleRemove() {
      if (!this.listTableData.length) {
        this.$showErrorMessage("未选中复选框");
      } else {
        this.$confirm("是否确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            if (contractType === 'change') {
              /**
               * 0=变更前清单，1=变更新增
               */
              // private Integer isOriginal;  0：不可删除
              const removeState = this.listTableData.some(
                _ => _.isOriginal === 0
              );
              if (removeState) {
                return this.$showErrorMessage(
                  "当前所选数据包含变更前清单，操作失败"
                );
              }
            }

            let temp = new Set(this.listTableData.map(n => n.onlyId));

            // 删除所选
            this.purchaseList = this.purchaseList.filter(
              _ => !temp.has(_.onlyId)
            );

            // 回显框架协议
            this.setAgreementSelectTableList(temp);

            // 回显采购计划
            this.planSelectTableList = this.planSelectTableList.filter(
              _ => !temp.has(_.onlyId)
            );

            // 回显采购方案
            this.programmeSelectTableList =
              this.programmeSelectTableList.filter(_ => !temp.has(_.onlyId));

            // 重置复选框选中的数据
            this.listTableData = [];
            // this.$refs.purchaseList.clearSelection();

            this.setDetailedTableList();

            // 如果清单中没有协议，则清除基础信息中的协议编号
            // const protocalCodeStatus = this.purchaseList.some(
            //   _ => _.pkPurmatdetl
            // );
            // if (!protocalCodeStatus) {
            //   this.setRemoveInventoryListStatus(true);
            // }

            if (!this.purchaseList.length) {
              this.$bus.$emit("setPriceSum", {
                setContractPriceIncludeTax: "",
                setContractPriceExcludeTax: ""
              });
            }
          })
          .catch(() => { });
      }
    },

    // 批量设置
    handlerChange(val) {
      // 查找符合条件的索引值
      const index = this.purchaseList.findIndex(
        n => n.onlyId === this.rowParams.onlyId
      );

      // 设置税率
      if (this.listSettingsStatus === "taxRate") {
        if (!this.listTableData.length) {
          this.purchaseList.map(m => {
            if (val.taxRatePercent) {
              this.$set(m, "taxRatePercent", val.taxRatePercent);
            }
            if (val.taxRateCode) {
              this.$set(m, "taxRateCode", val.taxRateCode);
            }

            // 触发行计算
            this.testColumn(null, m, "blur", "currentUnitPriceIncludeTax");
          });
        } else {
          this.listTableData.map(n => {
            this.purchaseList.map(m => {
              if (n.onlyId === m.onlyId) {
                if (val.taxRatePercent) {
                  this.$set(m, "taxRatePercent", val.taxRatePercent);
                }
                if (val.taxRateCode) {
                  this.$set(m, "taxRateCode", val.taxRateCode);
                }

                // 触发行计算
                this.testColumn(null, m, "blur", "currentUnitPriceIncludeTax");
              }
            });
          });
        }
      }

      // 设置多行地址
      if (this.listSettingsStatus === "address") {
        if (!this.listTableData.length) {
          this.purchaseList.map(m => {
            // 大区
            this.$set(m, "deliveryAreaName", val.deliveryAreaName);
            this.$set(m, "deliveryAreaCode", val.deliveryAreaCode);
            // 省
            this.$set(m, "provinceName", val.provinceName);
            this.$set(m, "province", val.province);
            // 市
            this.$set(m, "cityName", val.cityName);
            this.$set(m, "city", val.city);
            // 区
            this.$set(m, "countyName", val.countyName);
            this.$set(m, "county", val.county);
            // 详细地址
            this.$set(m, "deliveryPoints", val.deliveryPoints);
            // 拼接详细信息
            this.$set(
              m,
              "address",
              (val.deliveryAreaName || "") +
              (val.provinceName || "") +
              (val.cityName || "") +
              (val.countyName || "") +
              (val.deliveryPoints || "")
            );
          });
        } else {
          this.listTableData.map(n => {
            this.purchaseList.map(m => {
              if (n.onlyId === m.onlyId) {
                // 大区
                this.$set(m, "deliveryAreaName", val.deliveryAreaName);
                this.$set(m, "deliveryAreaCode", val.deliveryAreaCode);
                // 省
                this.$set(m, "provinceName", val.provinceName);
                this.$set(m, "province", val.province);
                // 市
                this.$set(m, "cityName", val.cityName);
                this.$set(m, "city", val.city);
                // 区
                this.$set(m, "countyName", val.countyName);
                this.$set(m, "county", val.county);
                // 详细地址
                this.$set(m, "deliveryPoints", val.deliveryPoints);
                // }
                // 拼接详细信息
                this.$set(
                  m,
                  "address",
                  (val.deliveryAreaName || "") +
                  (val.provinceName || "") +
                  (val.cityName || "") +
                  (val.countyName || "") +
                  (val.deliveryPoints || "")
                );
              }
            });
          });
        }
      }

      // 设置单行地址
      if (this.listSettingsStatus === "rowAddress") {
        const replaceObj = this.purchaseList[index];
        // 大区
        this.$set(replaceObj, "deliveryAreaName", val.deliveryAreaName);
        this.$set(replaceObj, "deliveryAreaCode", val.deliveryAreaCode);
        // 省
        this.$set(replaceObj, "provinceName", val.provinceName);
        this.$set(replaceObj, "province", val.province);
        // 市
        this.$set(replaceObj, "cityName", val.cityName);
        this.$set(replaceObj, "city", val.city);
        // 区
        this.$set(replaceObj, "countyName", val.countyName);
        this.$set(replaceObj, "county", val.county);
        // 详细信息
        this.$set(replaceObj, "deliveryPoints", val.deliveryPoints);
        // 拼接显示
        this.$set(
          replaceObj,
          "address",
          val.deliveryAreaName +
          val.provinceName +
          val.cityName +
          val.countyName +
          val.deliveryPoints
        );
      }
    },

    // 根据返回状态显示不同的文字颜色
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (
        (["currentMeasuringUnit"].includes(column?.property) &&
          row.matResource === "3") ||
        ["address"].includes(column?.property)
      ) {
        return { color: "#0089EF", cursor: "pointer" };
      }
    },

    // 行点击事件
    handleRowClick(row, column, event) {
      if (
        (["currentMeasuringUnit"].includes(column?.property) &&
          row.matResource === "3") ||
        ["address"].includes(column?.property)
      ) {
        this.rowParams = row;
        // 计量单位
        if (column.property === "currentMeasuringUnit") {
          // 在这里设置单位换算回显
          this.form.a = row.baseMeasuringUnit; // 基础单位
          this.form.b = row.currentMeasuringUnit; // 换算单位
          this.form.c = row.baseProportion; // 基础比列,默认1
          this.form.d = row.currentProportion; // 换算比列
          this.dialogVisible = true;
        }
        // 交货地点
        if (column.property === "address") {
          this.listSettingsDetail = cloneDeep(row);
          this.listSettingsDialogTitle = "设置地点";
          this.listSettingsStatus = "rowAddress";
          this.$refs.listSettings.showDialogVisible = true;
          this.$nextTick(() => {
            this.$refs.listSettings.init();
          });
        }
      }
    },

    // dropdown 事件
    handleCommand(val) {
      this.listSettingsStatus = val;
      this.listSettingsDialogTitle = this.listSettingsMap[val];

      this.$refs.listSettings.showDialogVisible = true;

      if (val === "address") {
        this.$nextTick(() => {
          this.$refs.listSettings.init();
        });
      }
    },

    // 设置换算单位取消
    dialogBeforeClose() {
      this.dialogVisible = false;
    },

    // 设置换算单位确认
    dialogConfim() {
      if (Number(this.form.c) > 0 && Number(this.form.d) > 0) {
        this.$confirm("请注意，换算单位将会清空采购清单数", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            // 查找选择的单位及编码
            const { dicKey, dicValue } =
              this.Enum.currentMeasuringUnitList.find(
                _ => _.dicValue === this.form.b
              );

            // 查找符合条件的索引值
            const index = this.purchaseList.findIndex(
              n => n.onlyId === this.rowParams.onlyId
            );
            // 深拷贝赋值
            const replaceObj = cloneDeep(this.purchaseList)[index];
            replaceObj.isConversion = 1;
            replaceObj.baseMeasuringUnit = this.rowParams.baseMeasuringUnit; // 基础计量单位
            replaceObj.baseMeasuringUnitCode =
              this.rowParams.baseMeasuringUnitCode;

            replaceObj.currentMeasuringUnit = dicValue; // 当前计量单位
            replaceObj.currentMeasuringUnitCode = dicKey;

            replaceObj.baseProportion = this.form.c; // 基础比列,默认1
            replaceObj.currentProportion = this.form.d; // 换算比列
            replaceObj.baseUnitPriceIncludeTax =
              this.rowParams.currentUnitPriceIncludeTax; // 基础含税单价
            replaceObj.baseNum = this.rowParams.currentNum; // 基础采购数量

            // 清空基础数据
            replaceObj.currentNum = ""; // 数量
            replaceObj.currentChangeAmtExcludeTax = ""; // 不含税金额
            replaceObj.currentUnitPriceExcludeTax = ""; // 不含税单价
            // replaceObj.currentUnitPriceIncludeTax = ""; // 含税单价
            replaceObj.currentChangeAmtIncludeTax = ""; // 含税金额

            // 替换表格中的数据
            this.purchaseList.splice(index, 1, replaceObj);

            this.dialogVisible = false;
            this.form = {
              a: "",
              b: "",
              c: "",
              d: ""
            };

            this.setDetailedTableList();
          })
          .catch(() => { });
      } else {
        this.$showErrorMessage("比例必须为数字，并且大于0！");
      }
    },

    // 暂存提交验证
    beforeSubmitTemp() {
      return new Promise((resolve, reject) => {
        const curPriceLengthStatus = this.purchaseList.some(
          _ => !this.getInputRule(_.currentChangeAmtIncludeTax)
        );
        if (!curPriceLengthStatus) return resolve(this.purchaseList);
        reject("third");
        return this.$showErrorMessage(
          "采购清单中含税金额合计超出最大长度限制，请重新编辑含税单价或数量！"
        );
      });
    },

    // 表格提交验证
    beforeSubmitList() {
      return new Promise((resolve, reject) => {
        const curPriceLengthStatus = this.purchaseList.some(
          _ => !this.getInputRule(_.currentChangeAmtIncludeTax)
        );
        const numEmptyStatus = this.purchaseList.some(_ => _.currentNum === "");
        const numStatus = this.purchaseList.some(_ => _.currentNum === "0.000");
        const priceEmptyStatus = this.purchaseList.some(
          _ => _.currentUnitPriceIncludeTax === ""
        );
        const priceStatus = this.purchaseList.some(
          _ => _.currentUnitPriceIncludeTax === "0.00"
        );
        if (curPriceLengthStatus) {
          reject("third");
          return this.$showErrorMessage(
            "采购清单中含税金额合计超出最大长度限制，请重新编辑含税单价或数量！"
          );
        }
        if (numEmptyStatus) {
          reject("third");
          return this.$showErrorMessage("采购清单中数量不能为空！");
        }
        if (contractType === 'draft' && numStatus) {
          reject("third");
          return this.$showErrorMessage("采购清单中数量不能为 0！");
        }
        if (priceEmptyStatus) {
          reject("third");
          return this.$showErrorMessage("采购清单中含税单价不能为空！");
        }
        if (priceStatus) {
          reject("third");
          return this.$showErrorMessage("采购清单中含税单价不能为 0！");
        }

        const taxRateStatus = this.purchaseList.every(_ => _.taxRatePercent);
        // 不是多税率
        if (!this.getMultiRateCode) return resolve(this.purchaseList);
        // 是多税率
        if (!taxRateStatus) {
          reject("third");
          return this.$showErrorMessage("采购清单中税率为必填项，请编辑后重试");
        }
        resolve(this.purchaseList);
      });
    },

    // 提交验证
    handleSubmit() {
      return new Promise(async (resolve, reject) => {
        if (this.purchaseList.length) {
          try {
            const temp = await this.beforeSubmitList();
            resolve(temp);
          } catch (error) {
            reject(error);
          }
        } else {
          this.$showErrorMessage("采购清单为必填项，请编辑后重试");
          reject("third");
        }
      });
    },

    // 校验单价是否合法
    handleBlur($event, row, val) {
      if (!row[val]) return;
      if (row.priceType && [1, 2].includes(row.priceType)) {
        if (row[val] > row.maxPrice) {
          row[val] = row.maxPrice;
        }
      }
      if (row.priceType && row.priceType === 2) {
        if (row[val] < row.minPrice) {
          row[val] = row.minPrice;
        }
      }

      this.testColumn($event, row, "blur", "currentUnitPriceIncludeTax");
    },

    // 回显框架协议
    setAgreementSelectTableList(temp) {
      this.agreementSelectTableList = this.agreementSelectTableList.filter(
        _ => !temp.has(_.onlyId)
      );
      this.setEchoProtocalData(this.agreementSelectTableList);
    },

    setDetailedTableList() {
      this.tableLoading = showLoading();

      this.$nextTick(() => {
        // 这样设置大量数据的表格
        this.$refs.purchaseList.reloadData(this.purchaseList);

        this.timer = setTimeout(() => {
          if (this.tableLoading !== null) {
            this.tableLoading.close();
            this.tableLoading = null;
          }
          this.$refs.purchaseList.doLayout();
        }, 500);
      });
    },

    // opre-验证合同清单引用状态
    checkConcBillReference(row) {
      checkConcBillReference({ id: row.id }).then(res => {
        if (res.data.data.flag === "1") {
          this.$showErrorMessage("该物资清单已被引用");
        } else {
          this.form.a = row.currentMeasuringUnit;
          this.rowParams = row;
          this.dialogVisible = true;
        }
      });
    },

    thirdCategoriesTooltip(row) {
      return `单位转换设置：${row.baseProportion} ${row.baseMeasuringUnit} = ${row.currentProportion} ${row.currentMeasuringUnit}`;
    },

    getInputRule(val) {
      const reg = /(^(\d{0,11})\.(\d{0,8})$)|(^\d{0,20}$)/;
      return reg.test(val);
    },

    getType(obj) {
      return Object.prototype.toString
        .call(obj)
        .replace(/^\[object (\S+)\]$/, "$1");
    },

    ...mapActions([
      "setEchoProtocalData",
      "setShowDoubleTable",
      "setPurchaseListStatus",
      "setRemoveInventoryList",
      "setRemoveInventoryListStatus",
      "setProtocalCode",
      "setListInputValStatus" // 初始化不让清单列表触发计算
    ])
  },
  computed: {
    ...mapState(["contractDraft"]),
    ...mapGetters([
      "getMultiRateCode",
      "getProtocalData",
      "getDelectList",
      "getTableHeadRuleNode",
      "getMultiRateStatus",
      "getAgreementSelectStatus",
      "getSourceRoute"
    ])
  },
  watch: {
    isShow: {
      handler(newVal) {
        if (newVal) {
          this.$refs.purchaseList.doLayout();
        }
      }
    },
    contractDraft: {
      deep: true,
      immediate: true,
      handler(newVal) {
        this.programmeOptionalParams = {
          ...this.programmeOptionalParams,
          // 给采购方案添加 是否海外采购 参数
          isoverseas: newVal.isOverseas,
          // 给采购方案添加 orgid 参数
          reportOrgId: newVal.orgId,
          // 给采购方案添加 供应商code 参数
          supcode: newVal.supplierData.supplierCode,
          // 给采购方案添加 币种 参数
          currencyCode: newVal.currencyObj.code
          // currencyName: newVal.currencyObj.name,
        };
        // 给采购计划添加参数
        this.planOptionalParams = {
          ...this.planOptionalParams,
          opunitOrgid: newVal.orgId,
          currencyCode: newVal.currencyObj.code
          // currencyName: newVal.currencyObj.name,
        };

        // 是否有供应商
        this.isMultiShow = !!newVal.supplierData.supplierCode;

        // 计算税额
        this.taxRateParams = newVal.taxRate;

        // 触发行计算
        this.purchaseList.map(item => {
          this.testColumn(null, item, "blur", "currentUnitPriceIncludeTax");
        });
      }
    },
    getMultiRateStatus(newVal) {
      this.multiRateStatus = newVal;
    },
    // 清空除物料目录的所有清单列表
    getRemoveInventoryList(newVal) {
      if (newVal) {
        this.purchaseList = this.purchaseList.filter(_ => !_.pkPurmatdetl);
        this.setDetailedTableList();
        this.$nextTick(() => {
          this.setRemoveInventoryList(false);
          this.setRemoveInventoryListStatus(true);
        });
      }
    },
    getMultiRateCode(newVal) {
      this.isMultiRate = newVal;

      // 切换多税率，重置清单中的计算
      this.purchaseList = this.purchaseList.map(n => ({
        ...n,
        currentNum: "", // 数量
        currentChangeAmtExcludeTax: "",
        currentUnitPriceExcludeTax: "",
        // currentUnitPriceIncludeTax: "", // 含税单价
        currentChangeAmtIncludeTax: "",
        rate: 0
      }));

      this.setDetailedTableList();
    },
    // 框架协议选择确认
    getProtocalData(newVal) {
      if (newVal.length) {
        const temp = cloneDeep(newVal);

        // 如果只有一条协议并且是特殊协议
        if (temp.length === 1 && !temp[0].materialsName) {
          this.setProtocalCode(temp[0]);
          this.purchaseList = this.purchaseList.filter(
            _ => _.matResource !== "0"
          );
          this.setDetailedTableList();
          return;
        }
        // 判断新选择的协议 code 是否不同
        const isUnifiedCode = temp.every(
          _ => _.protocalCode === temp[0].protocalCode
        );
        if (this.purchaseList.length) {
          // const isHomology = this.purchaseList.every(
          //   n => n.matResource === '0'
          // );
          // 判断已选择的列表中是否包含采购计划或者采购方案
          // if (!isHomology) {
          //   return this.$showErrorMessage(
          //     "已选择采购计划或者采购方案，添加清单失败"
          //   );
          // }
          if (!isUnifiedCode) {
            this.setPurchaseListStatus(false);
            // 回显框架协议
            this.setAgreementSelectTableList(
              new Set(this.listTableData.map(n => n.onlyId))
            );
            this.$showErrorMessage("当前已选择的协议编码不一致，添加清单失败");
            // this.setRemoveInventoryListStatus(true); // 清除基础信息的协议编码
          } else {
            this.setPurchaseListStatus(true);
            // 满足
            if (!temp.every(_ => _.materialsName)) {
              this.setPurchaseListStatus(true);

              this.purchaseList = this.purchaseList.filter(
                _ => _.matResource !== "0"
              );
              this.setDetailedTableList();
              return;
            }

            this.setSpecialProtocal(temp);
          }
        } else {
          if (!isUnifiedCode) {
            this.setPurchaseListStatus(false);
            // 回显框架协议
            this.setAgreementSelectTableList(
              new Set(this.listTableData.map(n => n.onlyId))
            );
            this.$showErrorMessage("当前已选择的协议编码不一致，添加清单失败");
            this.setRemoveInventoryListStatus(true); // 清除基础信息的协议编码
          } else {
            // this.setPurchaseListStatus(true);
            if (!temp.every(_ => _.materialsName)) {
              this.setPurchaseListStatus(true);

              this.purchaseList = this.purchaseList.filter(
                _ => _.matResource !== "0"
              );
              this.setDetailedTableList();
              return;
            }
            // 最后进行赋值
            // this.getAgreementDataToPurchaseList(temp);
            this.setSpecialProtocal(temp);

            this.setAgreementSelectTableList(
              new Set(this.purchaseList.map(n => n.onlyId))
            );
          }
        }
      }
    },
    // 框架协议删除
    getDelectList(newVal) {
      if (newVal) {
        this.purchaseList = this.purchaseList.filter(
          _ => _.matResource !== "0"
        );

        this.setDetailedTableList();
      }
    }
  }
});
